/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MODEL.UTIL;

import com.mysql.jdbc.Connection;
import java.sql.*;
import java.util.*;

/**
 *
 * @author linh
 */
public class MySqlDataAccessHelper {
    
    private Connection connection;

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public void Open() {
        try{
            Driver driver=new org.gjt.mm.mysql.Driver();
            DriverManager.registerDriver(driver);
            String connect="jdbc:mysql://localhost:3306/nama";
            Properties info=new Properties();
            info.setProperty("characterEncoding", "utf8");
            info.setProperty("user", "root");
            //info.setProperty("password", "");
            this.connection=(Connection) DriverManager.getConnection(connect,info);
        }catch(SQLException ex){System.out.println(ex.toString());}
    }
    
    public void Close(){
        try{
            this.connection.close();
        }
        catch(SQLException ex){
            System.out.println(ex.getMessage());
        }
    }
    
    public ResultSet executeQuery(String sql){
        ResultSet rs=null;
        try{
            Statement sm=this.connection.createStatement();
            rs=sm.executeQuery(sql);
        }
        catch(Exception ex){
            System.out.println(ex.getMessage());
        }
        return rs;
    }
    
    public int executeUpdate(String sql){
        int n=-1;
        try{
            Statement sm=this.connection.createStatement();
            n=sm.executeUpdate(sql);
        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }
        return n;
    }
    
    public ResultSet getResultSet(String sql,String tensach)
    {
       ResultSet rs=null;
       try{ 
           CallableStatement statement= this.connection.prepareCall(sql);
           statement.setString(1,tensach);
           statement.execute();  
           rs=statement.getResultSet();
       }catch(Exception ex){
            System.out.println(ex.getMessage());
       }return rs;
    }
 
    public void commit(){
    try{
        this.connection.commit();
    }
    catch(SQLException ex){
        System.out.println(ex.getMessage());}
    }
    
    public void rollback(){
    try{
        this.connection.rollback();
    }
    catch(SQLException ex){
        System.out.println(ex.getMessage());}
    }
    
    public void setAutoCommit(boolean test){
    try{
        this.connection.setAutoCommit(test);
    }
    catch(SQLException ex){
        System.out.println(ex.getMessage());}
    }
    
}